<?php

namespace app\systems\logic;
use think\facade\Request;
use app\admin\model\AdminModel;
use app\systems\model\SystemMqGroupModel;
use think\Model;
use app\admin\logic\BasicLogic;
use app\Systems\validate\SystemMqAdd;
use app\Systems\logic\SystemMqLogic;
use think\facade\Validate;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Config;
use app\data\util\Rabbitmq;

class MqGroupLogic extends BasicLogic
{
    /**
     * 根据id获取数据
     * @author cyz-andy
     * @Date 2021/1/20 14:20
     * @param $id
     * @param $cache
     * @return mixed
     */
    public static function get_mq_group_by_id($id,$cache=''){

        $key  = self::getCacheKey($id,__FUNCTION__);
        $list = Cache::store('redis')->get($key);
        if (!$list){
            $list = (new SystemMqGroupModel())->where(['id' => $id])->find();
            Cache::store('redis')->set($key,$list,7200);
        }
        return $list;
    }

    /**
     * 根据id获取数据
     * @param $id
     * @param $cache
     * @return mixed
     * @author cyz-andy
     * @Date 2021/1/20 14:20
     */
    public static function get_mq_group_by_ids($id, $cache = '')
    {
        $key  = self::getCacheKey($id, 'mq_group_data_');
        $list = Cache::store('redis')->get($key);
        if (!$list) {
            $list = (new SystemMqGroupModel())->where('id',$id)->find();
            $list = objectToArray($list);
            Cache::store('redis')->set($key,$list,7200);
        }
        return $list;
    }




    public static function get_mq_group_by_queue($queue,$cache=''){
        $key  = self::getCacheKey($queue,__FUNCTION__);
        $list = Cache::store('redis')->get($key);
        if (!$list){
            $list = (new SystemMqGroupModel())->where(['queue_name' => $queue])->find();
            $list = objectToArray($list);
            Cache::store('redis')->set($key,$list,7200);
        }
        return $list;
    }


    /**
     * 通过分组id推送对应的数据到队列上
     * @author cyz-andy
     * @Date 2021/1/8 21:30
     * @param $mqObj
     * @param $id
     * @param $message
     * @return bool
     */
    public static function mq_send_message_by_id($mqObj,$id,$message){

        try{
            $queueConfig = self::get_mq_group_by_id($id);
            $queueName = isset($queueConfig['queue_name']) ? $queueConfig['queue_name'] : '';
            $exchangeName = isset($queueConfig['exchange_name']) ? $queueConfig['exchange_name'] : '';
            $bindKeyName = isset($queueConfig['bind_key']) ? $queueConfig['bind_key'] : '';
            if (empty($queueName)) return '';
            ##如果mq对象参数没有传递，则根据分组id获取配置，重新创建连接
            if ( empty($mqObj) || !is_object($mqObj) )
            {
                $mqObj = app(rabbitmq::class, [$queueConfig['mq_config']]);
            }

            $queueData['queue_name'] = $queueName;
            $queueData['exchange_name'] = $exchangeName;
            $queueData['bind_key'] = $bindKeyName;
            return $mqObj->mq_send_message($message,$queueData);
        }catch (\Exception $e){
            return $e->getMessage();
        }
    }


    /**
     * 将指定数据推送到对应队列上
     * @author cyz-andy
     * @Date 2021/4/6 13:58
     * @param $mqObj
     * @param $queue_name
     * @param $message
     * @return string
     */
    public static function mq_send_message_by_queue($mqObj,$queue_name,$message,$attributes=array()){
        try{
            $queueConfig  = self::get_mq_group_by_queue($queue_name);
            $queueName    = isset($queueConfig['queue_name']) ? $queueConfig['queue_name'] : '';
            $exchangeName = isset($queueConfig['exchange_name']) ? $queueConfig['exchange_name'] : '';
            $bindKeyName  = isset($queueConfig['bind_key']) ? $queueConfig['bind_key'] : '';
            ##如果mq对象参数没有传递，则根据分组id获取配置，重新创建连接
            if ( empty($mqObj) || !is_object($mqObj) )
            {
                $mqObj = app(rabbitmq::class, [$queueConfig['mq_config']]);
            }
            $queueData['queue_name'] = $queueName;
            $queueData['exchange_name'] = $exchangeName;
            $queueData['bind_key'] = $bindKeyName;
            return $mqObj->mq_send_message($message,$queueData,$attributes);
        }catch (\Exception $e){
            return $e->getMessage();
        }
    }


    /**
     * @Notes:创建队列
     * @Author: TCP
     * @Date: 2021/10/8
     * @Time: 17:35
     * @param $queueConfig
     * @return string
     */
    public static function mq_careate_queue($queueConfig){
        try{
            $queueName    = isset($queueConfig['queue_name']) ? $queueConfig['queue_name'] : '';
            $exchangeName = isset($queueConfig['exchange_name']) ? $queueConfig['exchange_name'] : '';
            $bindKeyName  = isset($queueConfig['bind_key']) ? $queueConfig['bind_key'] : '';
            if(empty($queueName))  return  '队列名称：'.$queueName.',为空，请核实';
            $mqObj = app(rabbitmq::class, [$queueConfig['mq_config']]);
            $queueData['queue_name'] = $queueName;
            $queueData['exchange_name'] = $exchangeName;
            $queueData['bind_key'] = $bindKeyName;
            return $mqObj->mq_create_bind_queue($queueData);
        }catch (\Exception $e){
            return $e->getMessage();
        }
    }

    //解除绑定
    public static function mq_unbind_queue($queueConfig){
        try{
            $mqObj = app(rabbitmq::class, [$queueConfig['mq_config']]);
            unset($queueConfig['mq_config']);
            $mqObj->mq_un_bind_queue($queueConfig);
        }catch (\exception $e){
            return $e->getmessage();
        }
    }



    //消费队列
    public static function getQueueLength($queueName)
    {
        $len = 0;
        try{
            $queueconfig = self::get_mq_group_by_queue($queueName);
            $mqobj = app(rabbitmq::class, [$queueconfig['mq_config']]);
            unset($queueconfig['mq_config']);
            $len = $mqobj->getlength($queueName);
        } catch (\exception $e){
            return $e->getmessage();
        }
        return $len;
    }

    #查看消息
    public static function getLRange($queueName)
    {
        try {
            $queueconfig = self::get_mq_group_by_queue($queueName);
            $mqobj = app(rabbitmq::class, [$queueconfig['mq_config']]);
            $data = $mqobj->getMsg($queueName, false);
        } catch (\Throwable $e) {
            $data = $e->getmessage();
        }
        return $data;
    }


    /**
     * @param $mark
     * @param $fun
     * @return string
     * @desc 处理key值
     */
    public static function getCacheKey($mark,$fun){
        $original_class = trim(get_called_class(),'\\');   #原始调用类
        if (strrpos($original_class,'\\') !== false) $original_class = str_replace("\\",'.',$original_class);
        return $original_class.'.'.strtolower($fun).'_'.$mark;
    }





}